package com.spider.silence.utils;

import com.spider.silence.constant.Constant;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


/**
 * Created by qiuhao on 2017/5/2.
 */
public class ZipUtils {

    public static final String zipFilePath= Constant.ZIP_FOLDER;
    /**
     * 压缩多个文件
     * @param files 存放的要被压缩的文件集合
     */
    public static File ZipMultiFile(Map<String,File> files ,String speechId) {
        try {
            File f=new File(zipFilePath);
            if(!f.exists()){
                f.mkdirs();
            }
            File zipFile=new File(zipFilePath+speechId+".zip");
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            if(files!=null && files.size()>0){
                for(Map.Entry<String,File> entry:files.entrySet()){
                    File file=entry.getValue();
                    String filename= entry.getKey();
                    input = new FileInputStream(file);
                    zipOut.putNextEntry(new ZipEntry(filename));
                    int temp = 0;
                    while((temp = input.read()) != -1){
                        zipOut.write(temp);
                    }
                    input.close();
                    file.delete();

                }
            }
            zipOut.close();
            return zipFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 压缩多个文件
     * @param files 存放的要被压缩的文件集合
     */
    public static File ZipMultiFileByPath(Map<String,File> files ,String path,String speechId) {
        try {
            File f=new File(path);
            if(!f.exists()){
                f.mkdirs();
            }
            File zipFile=new File(path+"//"+speechId+".zip");
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            if(files!=null && files.size()>0){
                for(Map.Entry<String,File> entry:files.entrySet()){
                    File file=entry.getValue();
                    String filename= entry.getKey();
                    input = new FileInputStream(file);
                    zipOut.putNextEntry(new ZipEntry(filename));
                    int temp = 0;
                    while((temp = input.read()) != -1){
                        zipOut.write(temp);
                    }
                    input.close();
                    file.delete();

                }
            }
            zipOut.close();
            return zipFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}
